package com.fly.show.docker;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.SystemUtils;
import org.springframework.stereotype.Service;

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.Container;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DockerService
{
    List<DockerClient> dockerClients = new CopyOnWriteArrayList<>();
    
    @PostConstruct
    public void init()
    {
        if (SystemUtils.IS_OS_UNIX)
        {
            log.info("######## docker init by Unix socket");
            dockerClients.add(new DefaultDockerClient("unix:///var/run/docker.sock"));
        }
    }
    
    /**
     * 新增docker客户端
     * 
     * @param dockerclient
     * @see [类、类#方法、类#成员]
     */
    public void add(DockerClient dockerclient)
    {
        dockerClients.add(dockerclient);
    }
    
    /**
     * 返回活跃节点
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<DockerClient> getClients()
    {
        return dockerClients;
    }
    
    /**
     * 获取运行容器信息
     * 
     * @return
     * @throws InterruptedException
     * @throws DockerException
     * @see [类、类#方法、类#成员]
     */
    public List<Container> getContainers()
        throws DockerException, InterruptedException
    {
        if (dockerClients.isEmpty())
        {
            return Collections.emptyList();
        }
        DockerClient dockerClient = dockerClients.get(0);
        return dockerClient.listContainers();
    }
}
